<template>
  <el-dialog
    :title="title"
    :visible.sync="visible"
    width="800px"
    append-to-body
    :before-close="close"
  >
    <!-- 表单内容 -->
    <el-form :model="form" ref="form" label-width="150px" :rules="rulesA" v-if="form.type == 3">
      <el-form-item label="业主姓名" prop="merchantName">
        <el-input v-model="form.merchantName" placeholder="请输入业主姓名" maxlength="20" show-word-limit></el-input>
      </el-form-item>
      <el-form-item label="身份证号" prop="identityNo">
        <el-input v-model="form.identityNo" placeholder="请输入身份证号" maxlength="18"></el-input>
      </el-form-item>
      <el-form-item label="身份证号有效期类型" prop="identityValidityType" required>
        <el-radio-group v-model="form.identityValidityType">
          <el-radio label="0">非长期</el-radio>
          <el-radio label="1">长期</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="身份证号有效期" prop="identityValidDate" v-if="form.identityValidityType == 0">
        <el-date-picker
          v-model="form.identityValidDate"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyyMMdd"
          @change="identityValidDateChange"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="身份证号有效期" prop="identityBeginDate" v-if="form.identityValidityType == 1">
        <el-date-picker
          v-model="form.identityBeginDate"
          type="date" placeholder="请选择开始日期"
          value-format="yyyyMMdd"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="身份证国徽面照片" prop="certPhotoB">
        <image-upload v-model="form.certPhotoBUrl" :limit="1" @change="certPhotoBChange" :fileSize="2"/>
      </el-form-item>
      <el-form-item label="身份证人像面照片" prop="certPhotoA">
        <image-upload v-model="form.certPhotoAUrl" :limit="1" @change="certPhotoAChange" :fileSize="2"/>
      </el-form-item>

      <el-form-item label="联系电话" prop="contactPhone">
        <el-input v-model="form.contactPhone" placeholder="请输入联系电话" disabled></el-input>
      </el-form-item>
    </el-form>
    <!-- 企业信息表单 -->
    <el-form :model="form" ref="form" label-width="150px" :rules="rulesB" v-if="form.type == 1">
      <el-form-item label="企业名称" prop="merchantName">
        <el-input v-model="form.merchantName" placeholder="请输入企业名称"></el-input>
      </el-form-item>
      <el-form-item label="企业简称" prop="merchantShortName">
        <el-input v-model="form.merchantShortName" placeholder="请输入企业简称"></el-input>
      </el-form-item>
      <el-form-item label="统一社会信用证" prop="licenseCode">
        <el-input v-model="form.licenseCode" placeholder="请输入统一社会信用代码"></el-input>
      </el-form-item>
      <el-form-item label="营业执照有效标识" prop="licenseValidityType" required>
        <el-radio-group v-model="form.licenseValidityType">
          <el-radio label="0">非永久</el-radio>
          <el-radio label="1">永久</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="营业执照有效期" prop="licenseValidDate" v-if="form.licenseValidityType == 0">
        <el-date-picker
          v-model="form.licenseValidDate"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyyMMdd"
          @change="licenseValidDateChange"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="营业执照有效期" prop="licenseBeginDate" v-if="form.licenseValidityType == 1">
        <el-date-picker
          v-model="form.licenseBeginDate"
          type="date" placeholder="请选择开始日期"
          value-format="yyyyMMdd"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="营业执照注册地" prop="licenseLocation">
        <el-cascader :props="locationProps" v-model="form.licenseLocation"></el-cascader>
      </el-form-item>
      <el-form-item label="营业执照地址" prop="licenseAddress">
        <el-input v-model="form.licenseAddress" placeholder="请输入营业执照地址"></el-input>
      </el-form-item>
      <el-form-item label="营业执照" prop="licensePhoto">
        <image-upload v-model="form.licensePhotoUrl" :limit="1" @change="licensePhotoChange" :fileSize="2"/>
      </el-form-item>
      <el-form-item label="法人姓名" prop="legalName">
        <el-input v-model="form.legalName" placeholder="请输入法人姓名"></el-input>
      </el-form-item>
      <el-form-item label="法人身份证号" prop="identityNo">
        <el-input v-model="form.identityNo" placeholder="请输入身份证号" maxlength="18"></el-input>
      </el-form-item>
      <el-form-item label="身份证号有效期类型" prop="identityValidityType" required>
        <el-radio-group v-model="form.identityValidityType">
          <el-radio label="0">非长期</el-radio>
          <el-radio label="1">长期</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="身份证号有效期" prop="identityValidDate" v-if="form.identityValidityType == 0">
        <el-date-picker
          v-model="form.identityValidDate"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyyMMdd"
          @change="identityValidDateChange"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="身份证号有效期" prop="identityBeginDate" v-if="form.identityValidityType == 1">
        <el-date-picker
          v-model="form.identityBeginDate"
          type="date" placeholder="请选择开始日期"
          value-format="yyyyMMdd"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="法人身份证国徽面照片" prop="certPhotoB">
        <image-upload v-model="form.certPhotoBUrl" :limit="1" @change="certPhotoAChange" :fileSize="2"/>
      </el-form-item>
      <el-form-item label="法人身份证人像面照片" prop="certPhotoA">
        <image-upload v-model="form.certPhotoAUrl" :limit="1" @change="certPhotoBChange" :fileSize="2"/>
      </el-form-item>
      <el-form-item label="企业联系人姓名" prop="contactPhone">
        <el-input v-model="form.contactName" placeholder="请输入企业联系人姓名"></el-input>
      </el-form-item>
      <el-form-item label="企业联系电话" prop="contactPhone">
        <el-input v-model="form.contactPhone" placeholder="请输入企业联系电话" disabled></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submit" :loading="loading">确 定</el-button>
      <el-button @click="close">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { debounce } from '@/utils'
import {
  ownerOpenAccountCompanyProprietor,
  ownerOpenAccountProprietor,
  settleBankCardProprietor
} from '@/api/contract/proprietor'
import { listArea, listBank, listBankBranch, listCity, listProvince, uploadAuthImage } from '@/api/account/yima'
import { compareDate } from '@/utils/common/moment'

export default {
  name: 'proprietor-account',
  components: {},
  props: {
    value: {
      type: Boolean,
      default: false
    },
    title: {
      default: '分账平台信息'
    },
    data: {}
  },
  data() {
    return {
      loading: false,
      form: {},
      //配置省市区选择器
      locationProps: {
        lazy: true,
        lazyLoad(node, resolve) {
          const { level } = node
          setTimeout(() => {
            const data = []
            if (level === 0) {
              listProvince().then(res => {
                let list = res.data.map(item => {
                  return { value: item.provinceCode, label: item.provinceName }
                })
                data.push(...list)
                resolve(data)
              })
            } else if (level === 1) {
              listCity(node.value).then(res => {
                let list = res.data.map(item => {
                  return { value: item.cityCode, label: item.cityName }
                })
                data.push(...list)
                resolve(data)
              })
            } else if (level === 2) {
              console.log('node', node)
              let path = node.path
              listArea(path[0], path[1]).then(res => {
                let list = res.data.map(item => {
                  return { value: item.areaCode, label: item.areaName, leaf: true }
                })
                data.push(...list)
                resolve(data)
              })
            }
            resolve(data)
          })
        }
      },

      rulesA: {
        merchantName: [
          { required: true, message: '请输入业主姓名', trigger: 'blur' }
        ],
        identityNo: [
          { required: true, message: '请输入身份证号', trigger: 'blur' },
          {
            pattern: /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
            message: '请输入正确的身份证号',
            trigger: 'blur'
          }
        ],
        identityValidityType: [
          { required: true, message: '请选择身份证号有效期类型', trigger: 'blur' }
        ],
        identityValidDate: [
          { required: true, message: '请选择身份证号有效期', trigger: 'change' },
          {
            validator: (rule, value, callback) => {
              if (this.form.identityValidityType == 0) {
                // 结束日期小于当前日期
                if(compareDate(value[1], new Date(),'<')){
                  callback(new Error('结束日期不能小于当前日期'))
                }
              }
              callback()
            }
          }
        ],
        identityBeginDate: [
          { required: true, message: '请选择身份证号有效期', trigger: 'change' }
        ], //身份证号有效期开始时间
        certPhotoA: [
          { required: true, message: '请上传身份证人像面照片', trigger: 'change' }
        ],
        certPhotoB: [
          { required: true, message: '请上传身份证背面照片', trigger: 'change' }
        ],
        contactPhone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' }
        ]
      },
      rulesB: {
        merchantName: [
          { required: true, message: '请输入企业名称', trigger: 'blur' }
        ],
        merchantShortName: [
          { required: true, message: '请输入企业简称', trigger: 'blur' }
        ],
        licenseCode: [
          { required: true, message: '请输入统一社会信用代码', trigger: 'blur' }
        ],
        licenseValidityType: [
          { required: true, message: '请选择营业执照有效标识', trigger: 'blur' }
        ],
        licenseValidDate: [
          { required: true, message: '请选择营业执照有效期', trigger: 'change' }
        ],
        licenseBeginDate: [
          { required: true, message: '请选择营业执照有效期', trigger: 'change' }
        ],
        licenseLocation: [
          { required: true, message: '请选择营业执照注册地', trigger: 'change' }
        ],
        licenseAddress: [
          { required: true, message: '请输入营业执照地址', trigger: 'blur' }
        ],
        licensePhoto: [
          { required: true, message: '请上传营业执照', trigger: 'change' }
        ],
        legalName: [
          { required: true, message: '请输入法人姓名', trigger: 'blur' }
        ],
        identityNo: [
          { required: true, message: '请输入法人身份证号', trigger: 'blur' },
          {
            pattern: /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
            message: '请输入正确的身份证号',
            trigger: 'blur'
          }
        ],
        identityValidityType: [
          { required: true, message: '请选择身份证号有效期类型', trigger: 'blur' }
        ],
        identityValidDate: [
          { required: true, message: '请选择身份证号有效期', trigger: 'change' }
        ],
        identityBeginDate: [
          { required: true, message: '请选择身份证号有效期', trigger: 'change' }
        ], //身份证号有效期开始时间
        certPhotoA: [
          { required: true, message: '请上传身份证人像面照片', trigger: 'change' }
        ],
        certPhotoB: [
          { required: true, message: '请上传身份证背面照片', trigger: 'change' }
        ],
        contactName: [
          { required: true, message: '请输入企业联系人姓名', trigger: 'blur' }
        ],
        contactPhone: [
          { required: true, message: '请输入企业联系电话', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    visible: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('input', val)
      }
    }

  },
  watch: {
    value: {
      handler(newVal, oldVal) {
        if (newVal) {
          this.init()
        }
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    init() {
      this.reset()
    },
    reset() {
      if (this.data.proprietorType == 2) {
        this.form = {
          type: '1', //业主类型: 1企业 3个人
          merchantName: '', //企业名
          merchantShortName: '', //企业简称
          licenseCode: '', //统一信用代码
          licenseBeginDate: '', //营业执照开始时间
          licenseEndDate: '', //营业执照结束时间
          licenseValidDate: null, //营业执照有效期
          licenseValidityType: '0', //1：永久，0：非永久，默认0
          licenseLocation: [], //营业执照所在地
          licenseProvinceCode: '', //营业执照省code(翼码地区code)
          licenseCityCode: '', //营业执照市code(翼码地区code)
          licenseAreaCode: '', //营业执照区code(翼码地区code)
          licenseAddress: '', //营业执照地址
          legalName: '', //法人
          identityNo: '', //法人身份证号
          identityBeginDate: '', //身份证号有效期开始时间
          identityEndDate: '', //身份证号有效期结束时间
          identityValidityType: '0', //身份证有效期类型 1：长期，0：非长期
          contactName: '', //企业联系人
          contactPhone: this.data.proprietorMobile, //企业联系电话
          certPhotoA: '', //身份证人像面照片(翼码图片上传id)
          certPhotoB: '', //身份证国徽面照片(翼码图片上传id)
          licensePhoto: '' //营业执照id(翼码图片上传)
        }
      } else {
        this.form = {
          type: '3', //业主类型: 1企业 3个人
          merchantName: '', //业主姓名
          legalName: '', //法人
          identityNo: '', //业主身份证号
          identityBeginDate: '', //身份证号有效期开始时间
          identityEndDate: '', //身份证号有效期结束时间
          identityValidDate: null, //身份证有效期
          identityValidityType: '0', //身份证有效期类型 1：长期，0：非长期
          contactPhone: this.data.proprietorMobile, //联系电话
          certPhotoA: '', //身份证人像面照片(翼码图片上传id)
          certPhotoAUrl: '', //身份证人像面照片(翼码图片上传url)
          certPhotoB: '', //身份证国徽面照片(翼码图片上传id)
          certPhotoBUrl: '' //身份证背面照片(翼码图片上传url)
        }
      }
      this.resetForm('form')

    },
    // 营业执照有效期改变(非永久)
    licenseValidDateChange(val) {
      if (!val) return
      this.form.licenseBeginDate = val[0]
      this.form.licenseEndDate = val[1]
    },
    // 身份证有效期改变（非长期）
    identityValidDateChange(val) {
      if (!val) return
      this.form.identityBeginDate = val[0]
      this.form.identityEndDate = val[1]
    },
    // 上传身份证人像面照片
    certPhotoAChange(fileList, file) {
      if (!file.raw) return
      this.handleUploadAuthImage(file, '01')
    },
    // 上传身份证国徽照片
    certPhotoBChange(fileList, file) {
      if (!file.raw) return
      this.handleUploadAuthImage(file, '02')
    },
    // 上传营业执照
    licensePhotoChange(fileList, file) {
      if (!file.raw) return
      this.handleUploadAuthImage(file, '03')
    },
    // 上传图片
    handleUploadAuthImage(file, type) {
      if (!file.raw) return
      this.loading = true
      let form = new FormData()
      form.append('file', file.raw)
      uploadAuthImage(form, type).then(res => {
        if (type === '01') {
          this.form.certPhotoA = res.data
        } else if (type === '02') {
          this.form.certPhotoB = res.data
        } else if (type === '03') {
          this.form.licensePhoto = res.data
        }
        this.loading = false
      }).catch(err => {
        console.log(err)
        if (type === '01') {
          this.form.certPhotoAUrl = ''
        } else if (type === '02') {
          this.form.certPhotoBUrl = ''
        } else if (type === '03') {
          this.form.licensePhotoUrl = ''
        }
        this.loading = false
      })
    },
    // 提交表单
    submit: debounce(function() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.loading = true
          let action = null
          if (this.data.proprietorType == 2) {
            this.form.licenseProvinceCode = this.form.licenseLocation[0]
            this.form.licenseCityCode = this.form.licenseLocation[1]
            this.form.licenseAreaCode = this.form.licenseLocation[2]
            action = ownerOpenAccountCompanyProprietor
          } else {
            action = ownerOpenAccountProprietor
          }
          action(this.form, this.data.proprietorId).then(res => {
            this.$message.success(res.msg)
            this.visible = false
            this.$emit('success')
            this.loading = false
          }).catch(err => {
            console.log(err)
            this.loading = false
          })
        } else {
          return false
        }
      })
    }, 500, true),
    close() {
      this.visible = false
    }
  }
}
</script>


<style scoped lang="scss">
::v-deep .el-dialog__body {
  max-height: 80vh !important;
  overflow-y: auto;
}

.qrcode-container {
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
  height: 100%;

  .qrcode-container__qrcode {
    height: 200px;
    height: 200px;
  }
}

</style>
